from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer

from common import constants
from config.dynamic_configuration import ConfigurationFactory


class ConfigFileChangeHandler(FileSystemEventHandler):
    observer = None

    def __init__(self):
        self.conf_suffix = constants.CONF_SUFFIX

    def on_modified(self, event):
        if event.src_path.endswith(f'.{self.conf_suffix}'):
            ConfigurationFactory.refresh_configuration()

    @classmethod
    def start_file_monitor(cls):
        """启动文件监控"""
        if cls.observer is None:
            cls.observer = Observer()
            event_handler = cls()
            cls.observer.schedule(event_handler, path=constants.CONF_DIRECTORY, recursive=False)
            cls.observer.start()

    @classmethod
    def stop_file_monitor(cls):
        """停止文件监控"""
        if cls.observer is not None:
            cls.observer.stop()
            cls.observer.join()
            cls.observer = None
